import { request } from "../../request/index.js"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        goodsObj: {},
        isCollect: false
    },
    //商品对象
    GoodsList: {},
    /**
     * 生命周期函数--监听页面加载
     */
    onShow: function() {
        let pages = getCurrentPages();
        let currentPage = pages[pages.length - 1]
        let options = currentPage.options
        const { goods_id } = options
        this.getGoodsDetail(goods_id);


    },
    // 获取商品详情数据
    async getGoodsDetail(goods_id) {
        const goodsObj = await request({ url: "/goods/detail", data: { goods_id } });
        this.GoodsList = goodsObj;
        // 得到缓存中的收藏数组
        let collect = wx.getStorageSync("collect") || [];
        // 判断是否被收藏
        let isCollect = collect.some(v => v.goods_id === this.GoodsList.goods_id)
        this.setData({
            goodsObj: {
                goods_name: goodsObj.goods_name,
                goods_price: goodsObj.goods_price,
                //iphone 手机不支持 webp
                goods_introduce: goodsObj.goods_introduce.replace(/\.webp/g, '.jpg'),
                pics: goodsObj.pics
            },
            isCollect
        })
    },
    // 点击图片 放大
    handlePrevewImage(e) {
        // 先构造图片数组
        const urls = this.GoodsList.pics.map(v => v.pics_mid);
        //接受 传递过来的url
        const current = e.currentTarget.dataset.url
        wx.previewImage({
            current,
            urls
        });
    },
    // 加入购物车
    handleCartAdd() {
        // 获取缓存中的购物车 数组
        let cart = wx.getStorageSync("cart") || [];
        // 判断商品对象是否存在于购物车数组
        let index = cart.findIndex(v => v.goods_id === this.GoodsList.goods_id);
        if (index == -1) {
            // 不存在 第一次添加
            this.GoodsList.num = 1;
            this.GoodsList.checked = true;
            cart.push(this.GoodsList);
        } else {
            // 已经存在 数量加1
            cart[index].num++;
        }
        // 存入缓存
        wx.setStorageSync("cart", cart);
        // 弹窗提示
        wx.showToast({
            title: '加入成功',
            icon: 'success',
            mask: true
        });
    },
    // 点击收藏
    handleCollect() {
        let collect = wx.getStorageSync("collect") || [];
        let index = collect.findIndex(v => v.goods_id === this.GoodsList.goods_id);
        // index !=-1 表示已经收藏过了
        if (index != -1) {
            collect.splice(index, 1);
            wx.showToast({
                title: '取消成功',
                icon: 'success',
                mask: true,
            });
        } else {
            //没有收藏
            collect.push(this.GoodsList);
            wx.showToast({
                title: '收藏成功',
                icon: 'success',
                mask: true,
            });
        }
        wx.setStorageSync("collect", collect);
        this.setData({
            isCollect: !this.data.isCollect
        })
    }
})